package com.mlan.userap.okhttp;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;

import com.mlan.userap.AppConfig;
import com.mlan.userap.MyAPP;
import com.mlan.userap.untils.CommTool;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;



public class UploadHelper {

    private final OkHttpClient client;

    public UploadHelper() {
        client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    // 自定义带进度的 RequestBody
    private class ProgressRequestBody extends RequestBody {
        private final File file;
        private final ProgressListener listener;
        private final MediaType mediaType;

        public ProgressRequestBody(File file, MediaType mediaType, ProgressListener listener) {
            this.file = file;
            this.listener = listener;
            this.mediaType = mediaType;
        }


        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public long contentLength() {
            return file.length();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            try (okio.Source source = Okio.source(file)) {

                long totalBytes = contentLength();
                long bytesUploaded = 0;

                okio.Buffer buffer = new okio.Buffer();
                long bytesRead;

                while ((bytesRead = source.read(buffer, 8192)) != -1) {
                    // 从 buffer 中读取指定数量的字节到 byteArray
                    byte[] byteArray = buffer.readByteArray(bytesRead);
                    sink.write(byteArray, 0, (int) bytesRead);
                    bytesUploaded += bytesRead;
                    if (listener != null) {
                        long finalBytesUploaded = bytesUploaded;
                        new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                            listener.onProgress(finalBytesUploaded, totalBytes);
                        });
                    }
                }

            }
        }
    }


    private class ProgressFileBody extends RequestBody {
        private final InputStream inputStream; // 使用 InputStream 替代 File
        private final long contentLength;
        private final ProgressListener listener;
        private final MediaType mediaType;

        public ProgressFileBody(InputStream inputStream, long contentLength, MediaType mediaType, ProgressListener listener) {
            this.inputStream = inputStream;
            this.contentLength = contentLength;

            this.listener = listener;
            this.mediaType = mediaType;
        }


        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public long contentLength() {
            return contentLength;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            try (okio.Source source = Okio.source(inputStream)) {

                long totalBytes = contentLength();
                long bytesUploaded = 0;

                okio.Buffer buffer = new okio.Buffer();
                long bytesRead;

                while ((bytesRead = source.read(buffer, 8192)) != -1) {
                    // 从 buffer 中读取指定数量的字节到 byteArray
                    byte[] byteArray = buffer.readByteArray(bytesRead);
                    sink.write(byteArray, 0, (int) bytesRead);
                    bytesUploaded += bytesRead;
                    if (listener != null) {
                        long finalBytesUploaded = bytesUploaded;
                        new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                            listener.onProgress(finalBytesUploaded, totalBytes);
                        });
                    }
                }

            }
        }
    }

    public void uploadVoiceFile(String url, File voiceFile, long time,
                                ProgressListener progressListener) {

        String posturl = url;
        if(!url.startsWith("http")) posturl = AppConfig.apiUrl+url;
        // 创建带进度的 RequestBody
        RequestBody fileBody = new ProgressRequestBody(
                voiceFile,
                MediaType.parse("audio/*"),
                progressListener
        );

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", voiceFile.getName(), fileBody)
                .addFormDataPart("time", time+"")
                .build();

        Request request = new Request.Builder()
                .url(posturl)
                .post(requestBody)
                .addHeader("token", AppConfig.token)
                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.printStackTrace();
                progressListener.onFailure(e);
                System.out.println("上传失败: " + e.getMessage());
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                progressListener.onResponse(response);

            }
        });
    }


    public void uploadImageFile(String url, Uri imageUri, ProgressListener progressListener) {

        String posturl = url;
        if(!url.startsWith("http")) posturl = AppConfig.apiUrl+url;

        try {
            InputStream inputStream = MyAPP.getContext().getContentResolver().openInputStream(imageUri);
            long contentLength = getContentLength(MyAPP.getContext(), imageUri);

            if (inputStream == null) {
                progressListener.onFailure(new IOException("无法打开图片流"));
                return;
            }
            String fileName = CommTool.getFileNameFromUri(MyAPP.getContext(), imageUri);
            // 创建带进度的 RequestBody
            ProgressFileBody fileBody = new ProgressFileBody(
                    inputStream,
                    contentLength,
                    MediaType.parse("image/*"),
                    progressListener
            );

            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", fileName, fileBody)
                    .build();

            Request request = new Request.Builder()
                    .url(posturl)
                    .post(requestBody)
                    .addHeader("token", AppConfig.token)
                    .build();

            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    e.printStackTrace();
                    progressListener.onFailure(e);
                    System.out.println("上传失败: " + e.getMessage());
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    progressListener.onResponse(response);

                }
            });
        }
        catch (Exception ex) {
            progressListener.onFailure(new IOException("打开文件异常"));
        }
    }
    // 获取文件大小
    private long getContentLength(Context context, Uri uri) {
        try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                if (sizeIndex != -1) {
                    return cursor.getLong(sizeIndex);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1; // 如果无法获取，返回-1
    }


}